package 力扣._142_环形链表;


public class Solution {
    static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }


    //快慢指针
    public ListNode detectCycle(ListNode head) {
        if (head == null || head.next == null)
            return null;
        ListNode slow = head;
        ListNode fast = head.next;
        ListNode t = head;
        //设到达环入口长度为a,相遇点距环入口顺时针为x,环长度为r
        //则，相遇时，快指针走过 2*(a+x)= n*r + x,  即 a = n*r-x
        //此时再令一指针从头出发，经过 a, 此时慢指针在环上经过 n*r -x,到达环上 n*r处，即环入口
        //此时二者刚好相交
        while (slow != fast) {
            if (fast == null || fast.next == null)
                return null;
            slow = slow.next;
            fast = fast.next.next;
        }
        slow = slow.next;   //边界条件
        while (t != slow) {
            t = t.next;
            slow = slow.next;
        }
        return t;
    }

    public static void main(String[] args) {
        ListNode t1 = new ListNode(3);
        ListNode t2 = new ListNode(2);
        ListNode t3 = new ListNode(0);
        ListNode t4 = new ListNode(-4);
        t1.next = t2;
        t2.next = t3;
        t3.next = t4;
        t4.next = t2;
        ListNode listNode = new Solution().detectCycle(t1);
        System.out.printf(String.valueOf(listNode.val));

    }
}